// pages/main/index.js
const app = getApp()
const siteinfo = require('../../siteinfo.js')
const util = require('../../utils/util.js')
Page({
    /**
     * 页面的初始数据
     */
    data: {
        bgImage: '', // 背景图
        title: [],
        showHeight: 220,
        savedNum: 0,
        cansWidth: 280,
        cansHeight: 280,
        avatarImage: "",
        currentFrame: {}, //目前选取的头像框
        frameImage: '', //选中的头像框
        bottomId: null,
        currentCategory: 1, //初始化类别
        categoryList: [], //相框分类
        assetsList: [], //相框
        imageList: [],
        status: true,
        // 分页加载相框参数
        page: 1, //当前第几页
        pagesize: 10, //每页条数
        show: false, //是否触发触底加载
        loading: true, //数据是否在加载中
        orderlist: [], //订单列表
        isEmpty: false, //是否显示暂无数据
    },
    async onLoad(options) {
        await this.getData()
        await this.paging()
        this.initScreen()
    },
    onShow() {
        if (app.globalData.imgSrc) {
            this.setData({
                avatarImage: app.globalData.imgSrc
            })
        }
    },
    /**
     * 获取后端数据
     */
    async getData() {
        const res = await util.getData({
            url: siteinfo.siteroot + '/api/avatar_home',
            data: {},
            method: "GET"
        })
        const {
            bgImage,
            title,
            categoryList
        } = res.data
        this.setData({
            bgImage,
            title,
            categoryList
        })
    },
    /**
     * 初始化屏幕
     */
    initScreen() {
        wx.getSystemInfo({
            success: res => {
                let height = res.windowHeight
                let showHeight = 220
                if (height > 900) {
                    showHeight = 340
                } else if (height > 850) {
                    showHeight = 330
                } else if (height > 700) {
                    showHeight = 300
                } else if (height > 600) {
                    showHeight = 240
                } else {
                    showHeight = 140
                }
                if (this.data.assetsList.length != 0 && this.data.currentCategory.length != 0) {
                    this.setData({
                        showHeight,
                        imageList: this.data.assetsList,
                        frameImage: this.data.assetsList[this.data.currentCategory - 1].url
                    })
                }
            }
        })
    },
    // 选择图片
    selectPicture(e) {
        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['album', 'camera'],
            camera: 'back',
            success: res => {
                console.log(res);
                this.setData({
                    avatarImage: res.tempFiles[0].tempFilePath
                })
            }
        })
    },
    /**
     * 去裁剪
     */
    toCropper() {
        wx.navigateTo({
            url: '/pages/cropper/cropper?imgSrc=' + this.data.avatarImage
        })
    },
    // 图片裁剪
    onMyEvent(e) {
        let avatarImage = e.detail.myevent
        if (avatarImage) {
            this.setData({
                status: false,
                avatarImage
            })
        }
    },
    //切换类型
    async imageListTab(e) {
        // 重置加载的相框数据
        this.setData({
            page: 1, //当前第几页
            pagesize: 10, //每页条数
            imageList: [],
            assetsList: []
        })
        // 导航控制
        let categroyId = e.currentTarget.dataset.categroyId
        this.setData({
            currentCategory: categroyId,
            savedNum: 0
        })
        // 初始化切换的类型
        await this.paging()
        // 默认选中第一个相框
        if (this.data.avatarImage) {
            this.changeAsset(this.data.assetsList[categroyId], 0)
        }
    },
    //选取头像挂件
    selectAvatarImage(e) {
        let index = e.currentTarget.dataset.index
        let url = e.currentTarget.dataset.url
        if (this.data.avatarImage) {
            this.setData({
                savedNum: index,
                currentFrame: url,
                frameImage: url
            })
        } else {
            wx.showToast({
                title: "请先选择图片",
                icon: "none",
                duration: 2000
            })
        }
    },
    // 左右切换
    cutover(e) {
        let type = e.currentTarget.dataset.type
        if (!this.data.avatarImage) {
            wx.showToast({
                title: "请先选择图片",
                icon: "none",
                duration: 2000
            })
            return
        }
        if (type == 'next') {
            if (this.data.savedNum < this.data.imageList.length - 1) {
                this.setData({
                    savedNum: ++this.data.savedNum,
                    frameImage: this.data.imageList[this.data.savedNum].url,
                    bottomId: "img" + this.data.savedNum
                })
            } else {
                wx.showToast({
                    title: "已经是最后一张",
                    icon: "none",
                    duration: 2000
                })
            }
        } else {
            if (this.data.savedNum) {
                this.setData({
                    savedNum: --this.data.savedNum,
                    frameImage: this.data.imageList[this.data.savedNum].url,
                    bottomId: "img" + this.data.savedNum
                })
            } else {
                wx.showToast({
                    title: "已经是第一张",
                    icon: "none",
                    duration: 2000
                })
            }
        }
    },
    // 选择挂件
    changeAsset(data, index) {
        if (this.data.avatarImage) {
            this.data.savedNum = index
            this.data.currentFrame = data[index]
        } else {
            wx.showToast({
                title: "请先选择图片",
                icon: "none",
                duration: 2000
            })
        }
    },
    /**
     * 分页加载挂件
     */
    async paging() {
        const {
            page,
            pagesize
        } = this.data;
        await util.getData({
            url: siteinfo.siteroot + '/api/avatar_changeFrameSort',
            data: {
                page,
                pagesize,
                sort: this.data.currentCategory
            },
            method: 'GET'
        }).then(res => {
            if (res.status_code == 200 && res.data) {
                if (!res.data.data) return

                let currentIndex = res.data.current_page;
                //后台返回的当前第几页
                let totalRows = res.data.total;
                //后台返回的总记录数
                if (this.data.imageList.length === totalRows) {
                    if (totalRows === 0) {
                        this.setData({
                            isEmpty: true
                        })
                    }
                    wx.showToast({
                        title: "没有了~",
                        icon: "none"
                    })
                    //如果数据已经加载完成，不让其继续执行
                    return
                }
                let tempList = res.data.data
                let nextIndex = tempList.length < 10 ? currentIndex : currentIndex + 1;
                //如果最后一页数据没有加载完成，再次触底还是请求该页数据
                let arrayList = [...this.data.imageList, ...tempList]
                this.setData({
                    imageList: arrayList,
                    assetsList: arrayList,
                    page: nextIndex,
                    loading: arrayList.length != totalRows,
                    isEmpty: arrayList.length <= 0
                })
            }
        })
    },
    // 分享
    share() {
        if (this.data.avatarImage) {
            wx.showShareMenu({
                withShareTicket: true,
                menus: ["shareAppMessage", "shareTimeline"]
            })
        }
    },
    // 页面分享参数
    onShareAppMessage() {
        return {
            title: this.data.title[Math.floor(Math.random() * 5)],
            // imageUrl: "https://api.taochuanda.cn/api/toux/1.jpg",
            path: "/pages/main/index"
        }
    },
    // 分享到朋友圈参数
    onShareTimeline() {
        return {
            title: this.data.title[Math.floor(Math.random() * 5)],
            // imageUrl: "https://api.taochuanda.cn/api/toux/2.jpg",
            path: "/pages/main/index"
        }
    },
    /**
     * 绘制头像
     */
    draw() {
        wx.showLoading({
            title: "处理中..."
        })
        if (this.data.avatarImage) {
            wx.createSelectorQuery().select('#canvas')
                .fields({
                    node: true,
                    size: true,
                    rect: true
                })
                .exec(res => {
                    // Canvas 对象
                    const canvas = res[0].node
                    // 渲染上下文
                    const ctx = canvas.getContext('2d')
                    // Canvas 画布的实际绘制宽高
                    const width = res[0].width
                    const height = res[0].height
                    // 初始化画布大小
                    const dpr = wx.getWindowInfo().pixelRatio
                    canvas.width = width * dpr
                    canvas.height = height * dpr
                    ctx.scale(dpr, dpr)
                    // 图片对象
                    const image = canvas.createImage() //本地背景图 
                    const imgs = canvas.createImage() //接口返回二维码图片
                    image.src = this.data.avatarImage // 可以是本地地址也可以是网络地址
                    imgs.src = this.data.frameImage // 可以是本地地址也可以是网络地址
                    imgs.onload = () => {
                        // ctx.drawImage(image, 0, 0, this.data.widthImg, this.data.heightImg)
                        ctx.drawImage(image, 0, 0, this.data.cansWidth, this.data.cansHeight)
                        ctx.drawImage(imgs, 0, 0, this.data.cansWidth, this.data.cansHeight)
                    }
                    setTimeout(() => {
                        this.saveCans(canvas)
                    }, 1000)
                })
        } else {
            wx.hideLoading()
            wx.showToast({
                title: "请先选择图片",
                icon: "none",
                duration: 2000
            })
        }
    },
    // 保存到相册
    async saveCans(canvas) {
        // 获取数据
        const res = await util.getData({
            url: siteinfo.siteroot + '/api/avatar_advert', //是否开启广告
            data: {},
            method: "GET"
        })
        wx.setStorageSync('appConfig', res.data)
        var appConfig = wx.getStorageSync('appConfig')
        // 判断广告是否开启
        if (appConfig.ad.videotrue) {
            let videoAd = null
            // 在页面中定义激励视频广告
            // 在页面onLoad回调事件中创建激励视频广告实例
            if (wx.createRewardedVideoAd) {
                videoAd = wx.createRewardedVideoAd({
                    adUnitId: appConfig.ad.video_adUnitId
                })
                console.log(appConfig.ad.video_adUnitId)
                videoAd.onLoad(() => {})
                videoAd.onError((err) => {})
            }
            videoAd.onClose((res) => {
                // 用户点击了【关闭广告】按钮
                // videoAd.offClose 清除以前的回调避免重复
                videoAd.offClose()
                if (res && res.isEnded) {
                    // 正常播放结束，可以下发游戏奖励
                    // 保存图片开始
                    wx.showLoading({
                        title: "保存..."
                    })
                    wx.canvasToTempFilePath({
                        canvas: canvas,
                        success: t => {
                            wx.hideLoading()
                            this.wxSaveAuth().then(function (res) {
                                wx.saveImageToPhotosAlbum({
                                    filePath: t.tempFilePath,
                                    success: function success(res) {
                                        // 正常保存成功清空缓存
                                        // wx.clearStorageSync()
                                        wx.showToast({
                                            title: "保存图片成功",
                                            icon: "success",
                                            duration: 2000
                                        })
                                    },
                                    fail: function fail(res) {
                                        wx.showToast({
                                            title: "保存图片失败",
                                            icon: "none",
                                            duration: 2000
                                        })
                                    }
                                })
                            })
                        },
                        fail: function fail(a) {
                            wx.hideLoading()
                        }
                    })
                    // 保存图片结束
                    // 积分结束     
                } else {
                    // 播放中途退出，不下发游戏奖励
                    wx.showToast({
                        title: '未看完无法保存',
                        icon: 'error',
                        duration: 1000 //持续的时间
                    })
                }
            })
            // 用户触发广告后，显示激励视频广告
            if (videoAd) {
                videoAd.show().catch(() => {
                    // 失败重试
                    videoAd.load().then(() => videoAd.show()).catch(err => {
                        console.log('激励视频 广告显示失败')
                    })
                })
            }
            wx.hideLoading()
        } else {
            wx.canvasToTempFilePath({
                canvas: canvas,
                success: t => {
                    console.log('绘制完成', t.tempFilePath);
                    wx.hideLoading()
                    this.wxSaveAuth().then(function (res) {
                        wx.saveImageToPhotosAlbum({
                            filePath: t.tempFilePath,
                            success(res) {
                                // 无广告保存成功清除缓存
                                //  wx.clearStorageSync()
                                wx.showToast({
                                    title: "保存图片成功",
                                    icon: "success",
                                    duration: 2000
                                })
                            },
                            fail(res) {
                                wx.showToast({
                                    title: "保存图片失败",
                                    icon: "none",
                                    duration: 2000
                                })
                            }
                        })
                    })
                },
                fail: function fail(a) {
                    wx.hideLoading()
                }
            })
        }
        // 判断广告是否开启结束
        // 获取结束
    },
    /**
     *  获取相册权限
     */
    wxSaveAuth() {
        return new Promise(function (resolve, reject) {
            wx.getSetting({
                success: function success(res) {
                    if (!res.authSetting['scope.writePhotosAlbum']) {
                        // 如果没有写入权限，则获取写入相册权限
                        wx.authorize({
                            scope: 'scope.writePhotosAlbum',
                            success: function success() {
                                resolve()
                            },
                            fail: function fail(err) {
                                reject(err) // 用户拒绝授权

                                wx.showModal({
                                    content: '检测到您没打开相册权限，是否去设置打开？',
                                    confirmText: '确认',
                                    cancelText: '取消',
                                    success: function success(res) {
                                        if (res.confirm) {
                                            wx.openSetting({
                                                success: function success(res) {}
                                            })
                                        }
                                    }
                                })
                            }
                        })
                    } else {
                        resolve()
                    }
                },
                fail: function fail(e) {
                    reject(e)
                }
            })
        })
    }
})